﻿using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace SmartMovieTime
{
    public partial class MovieTimeForm : Form
    {
        private string dataDir;
        private List<AtMovieMovieRow> movieRowList;

        public MovieTimeForm(string dir, string areaId, string theaterId, string theaterName)
        {
            InitializeComponent();
            dataDir = dir;
            lblTheaterName.Text = theaterName;
            LoadMovieTime(areaId, theaterId);
        }

        private void cbMovie_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearMovieTime();
            if (cbMovie.SelectedIndex >= 0)
            {
                string[] timeStringList = movieRowList[cbMovie.SelectedIndex].TimeList;
                if (timeStringList != null)
                {
                    foreach (string time in timeStringList)
                    {
                        //lvTime.Items.Add(time);
                        ListViewItem lvItem = new ListViewItem(time);
                        lvTime.Items.Add(lvItem);
                    }
                }
            }
        }

        private void menuClose_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            Close();
        }

        private void LoadMovieTime(string areaId, string theaterId)
        {
            string movieTimeFile = AtMovieTimeExtractor.GetMovieTimeTableFile(dataDir, areaId, theaterId);
            if (File.Exists(movieTimeFile))
            {
                //Load movie time table file
                TxtTable<AtMovieMovieRow> movieTable = new TxtTable<AtMovieMovieRow>();
                movieTable.LoadFromFile(movieTimeFile);
                AtMovieMovieRow movieRow = null;
                movieRowList = new List<AtMovieMovieRow>();
                while ((movieRow = movieTable.ReadNext()) != null)
                {
                    movieRowList.Add(movieRow);
                    cbMovie.Items.Add(movieRow.MovieName);
                }
                movieTable.Close();
                if (cbMovie.Items.Count > 0)
                {
                    cbMovie.SelectedIndex = 0;
                }
            }
        }

        private void ClearMovieTime()
        {
            lvTime.Clear();
        }

        private void lvTime_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Up)
            {
                if ((lvTime.Items.Count == 0) || (lvTime.Items[0].Focused))
                {
                    cbMovie.Focus();
                }
            }
        }
    }
}